<template>
    <div ref="imgDom" class="imgs" v-bind="$attrs">
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineProps } from 'vue'

const props = defineProps({
    src: {
        type: String,
        default: '',
    },
    showType: {
        type: String,
        default: 'contain',
    },
    bgColor: {
        type: String,
        default: '#f0f0f0',
    },
    bgImg: {
        type: String,
        default: '',
    },
    width: {
        type: String,
        default: '',
    },
    height: {
        type: String,
        default: '',
    },
})

function getImageUrl() {
    const imgObj = new Image()
    imgObj.src = props.src
    imgDom.value.style.backgroundSize = props.showType
    imgDom.value.style.backgroundColor = props.bgColor
    imgDom.value.style.backgroundRepeat = 'no-repeat'
    imgDom.value.style.backgroundPosition = props.position
    imgDom.value.style.width = props.width + 'px'
    imgDom.value.style.height = props.height + 'px'
    imgObj.onload = (evt) => {
        imgDom.value.style.backgroundImage = `url(${props.src})`
    }
    imgObj.onerror = () => {
        console.log('图片加载失败')
        imgDom.value.style.backgroundImage = `url(${props.bgImg})`
    }
}
onMounted(() => {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                // 元素进入视口时执行的操作
                // console.log('元素已进入视口')
                getImageUrl()
            } else {
                console.log('元素已离开视口')
            }
        })
    }, {
        threshold: 0.1 // 当10%的元素可见时触发
    })
    if (imgDom.value) {
        observer.observe(imgDom.value)
    }
    onUnmounted(() => {
        observer.disconnect()
    })
})
const imgDom = ref(null)

</script>
<style scoped>
.imgs {
    width: 100px;
    height: 100px;
    background-color: aqua;

}
</style>
